package com.junjie.checkin.websocket.manger;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 洪浚杰
 * @description
 * @date 2025/6/24 23:30
 */
@Component
public class WebSocketSessionManager {
    private final Map<String, String> userSessions = new ConcurrentHashMap<>();

    @EventListener
    public void handleSessionConnected(SessionConnectedEvent event) {
        String sessionId = event.getMessage().getHeaders().get("simpSessionId", String.class);
        Principal principal = event.getUser();
        if (principal != null) {
            userSessions.put(principal.getName(), sessionId);
        }
    }

    @EventListener
    public void handleSessionDisconnect(SessionDisconnectEvent event) {
        String sessionId = event.getSessionId();
        userSessions.values().removeIf(id -> id.equals(sessionId));
    }

    public String getSessionId(String username) {
        return userSessions.get(username).toString();
    }
}